﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace MetroToolbox.Interactivity
{
    public abstract class Behavior<T> : Behavior
    {
        protected override Type AssociatedType { get { return typeof(T); } }
    }

    public abstract class Behavior : DependencyObject, IAttachedObject
    {
        protected DependencyObject AssociatedObject { get; private set; }

        protected virtual Type AssociatedType { get { return typeof(DependencyObject); } }

        public void Attach(DependencyObject dependencyObject)
        {
            if (dependencyObject == null)
            {
                throw new ArgumentNullException("dependencyObject");
            }

            if (!AssociatedType.GetTypeInfo().IsAssignableFrom(dependencyObject.GetType().GetTypeInfo()))
            {
                throw new ArgumentException("Cannot attach to object, does not meet AssociatedType", "dependencyObject");
            }

            AssociatedObject = dependencyObject;
            OnAttached();
        }

        public void Detach()
        {
            OnDetaching();
            AssociatedObject = null;
        }

        protected virtual void OnAttached() { }

        protected virtual void OnDetaching() { }

        DependencyObject IAttachedObject.AssociatedObject { get { return this.AssociatedObject; } }
    }
}
